import React, {
  FC,
  ReactElement,
  useState,
  useMemo,
  useEffect,
} from 'react';
import { useLocation } from 'react-router-dom';
import { Toast } from '@douyinfe/semi-ui';
import { getFieldsGoodsServicesDetail } from '@/services';
import ItemOperate from './sub/ItemOperate';
import ShowDetail from './sub/ShowDetail';
import type { GoodsServiceDetailItem } from './types';

const FieldsGoodsServiceDetailPage: FC = (): ReactElement => {
  const routeLocation = useLocation();
  const [currentData, setCurrentData] = useState<GoodsServiceDetailItem>({});
  const [formLoading, setFormLoading] = useState<boolean>(false);

  const searchParams = useMemo(() => {
    const params = new URLSearchParams(routeLocation.search);
    return params;
  }, [routeLocation.search]);
  const currentId = useMemo(
    () => searchParams.get('id'),
    [searchParams]
  );
  const currentAction = useMemo(
    () => {
      const urlArr = routeLocation.pathname.split('/');
      return urlArr[urlArr.length - 1];
    },
    [searchParams]
  );

  useEffect(() => {
    switch (currentAction) {
      case 'create':
        // 创建
        break;
      case 'update':
        // 编辑
        getItemDetailById(currentId);
        break;
      case 'detail':
        // 查看
        getItemDetailById(currentId);
        break;
      default:
        break;
    }
  }, []);

  async function getItemDetailById(id: number | string) {
    setFormLoading(true);
    try {
      const { data, code, message } = await getFieldsGoodsServicesDetail(id);
      if (code !== 0) {
        throw new Error(message);
      }
      setCurrentData(data);
    } catch (e) {
      Toast.error(`请求出错了：${(e instanceof Error) ? e.message : 'Error'}`);
    }
    setFormLoading(false);
  }

  return (
    <div className="container-full">
      {currentAction === 'create' && (
        <ItemOperate type="create" />
      )}
      {currentAction === 'update' && (
        currentData.id && <ItemOperate type="update" id={currentData.id} initValues={currentData} />
      )}
      {currentAction === 'detail' && (
        <ShowDetail currentData={currentData} loading={formLoading} />
      )}
    </div>
  );
}

export default FieldsGoodsServiceDetailPage;
